# -*- coding: utf-8 -*-
import datetime

from openerp import models, fields, api


class bc_reserve_summary(models.Model):
    _name = 'bc.reserve.summary'

    company_id = fields.Many2one('res.company', default=lambda self: self.env.user.company_id)
    resouretype_id = fields.Many2one('bc.resouretype')
    startdate = fields.Date(default=datetime.date.today())
    enddate = fields.Date(default=datetime.date.today() + datetime.timedelta(days=30))
    summary_header = fields.Text('Summary Header')
    room_summary = fields.Text('Room Summary')

    @api.onchange('startdate', 'enddate')
    def get_room_summary(self):
        if not (self.startdate and self.enddate):
            return

        all_room_detail = []
        obj_contract_detail = self.env['bc.contract.detail']
        resource_objs = self.env['bc.resource'].search([])
        all_room_hear = self.get_heard()

        for resource in resource_objs:
            resource_detail = {}
            resource_detail.update({'name': resource.name or ''})

            room_list_stats = []
            for chk_date in all_room_hear:
                room_list_stats.append(
                    {'state': obj_contract_detail.get_state(resource.id, chk_date), 'date': chk_date})

            resource_detail.update({'value': room_list_stats})
            all_room_detail.append(resource_detail)

        all_room_hear.insert(0, 'Rooms')
        self.summary_header = str([{'header': all_room_hear}])
        self.room_summary = str(all_room_detail)

        return True

    def get_heard(self):
        """
        根据开始时间,结束时间,生成数组
        :return: 日期数组
        """
        _startdate = datetime.datetime.strptime(self.startdate, "%Y-%m-%d")
        _enddate = datetime.datetime.strptime(self.enddate, "%Y-%m-%d")

        date_range_list = []
        temp_date = _startdate
        while (temp_date <= _enddate):
            date_range_list.append(temp_date.strftime('%Y-%m-%d'))
            temp_date = temp_date + datetime.timedelta(days=1)

        return date_range_list
